using System.Collections.Generic;
using AutoMapper;
using microsoft_TODO.DTOs;
using microsoft_TODO.Models;
using microsoft_TODO.MongoCore;
using MongoDB.Bson;
using MongoDB.Driver;

namespace microsoft_TODO.ServiceCore.Services {
  public class ListService : IListService {
    IListRepository _listRepository;
    IMapper _mapper;
    public ListService (
      IListRepository listRepository,
      IMapper mapper) {
      _listRepository = listRepository;
      _mapper = mapper;
    }
    public List<CheckList<TaskWithIndex>> GetAllByUserId (string uid) {
      var res = _listRepository.GetAllList (u => u.UserId == uid);
      var newRes  = new List<CheckList<TaskWithIndex>>();
      foreach (var originCheckList in res)
      {
        var newCheckList = _mapper.Map<CheckList<TaskWithIndex>>(originCheckList);
        for (int i = 0; i < originCheckList.Tasks.Count; i++)
        {
            var newTask = _mapper.Map<TaskWithIndex>(originCheckList.Tasks[i]);
            newTask.Index = i;
            newCheckList.Tasks.Add(newTask);
        }
        newRes.Add(newCheckList);
      }
      return newRes;
    }

    public string GetTitleByListId (string lid) {
      return _listRepository.FirstOrDefault (u => u.Id == lid).Title;
    }

    public CheckList<Task> InsertNewList (NewListDto dto) {
      var entity = _mapper.Map<CheckList<Task>> (dto);
      var back = _listRepository.Insert (entity);
      return back;
    }

    public bool IsExistent (string id) {
      return _listRepository.IsExistent (u => u.Id == id);
    }

    public bool RemoveList (string id) {
      return _listRepository.Delete (u => u.Id == id && u.IsStatic == false);
    }

    public void ModifyTitle (ListTitleDto dto) {
       var update = Builders<CheckList<Task>>.Update.Set(u => u.Title, dto.Title).Set(u => u.Icon, dto.Icon);

      _listRepository.Update (
        u => u.Id == dto.Id,
        update);
    }
  }
}